<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>Jetpack -- (一)Lifecycle | 码行</title><meta name="author" content="Carl Su"><meta name="copyright" content="Carl Su"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="使用Lifecycle解耦页面与组件场景： Chronometer统计页面在前台时间使用Lifecycle之前： private lateinit var binding: ActivityMainBinding    private var elapsedTime:Long &#x3D; 0    override fun onCreate(savedInstanceState: Bundle?) &amp;#1">
<meta property="og:type" content="article">
<meta property="og:title" content="Jetpack -- (一)Lifecycle">
<meta property="og:url" content="https://devsu.top/posts/6ee0249e/index.html">
<meta property="og:site_name" content="码行">
<meta property="og:description" content="使用Lifecycle解耦页面与组件场景： Chronometer统计页面在前台时间使用Lifecycle之前： private lateinit var binding: ActivityMainBinding    private var elapsedTime:Long &#x3D; 0    override fun onCreate(savedInstanceState: Bundle?) &amp;#1">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img2.baidu.com/it/u=2072160848,356224098&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500">
<meta property="article:published_time" content="2020-08-05T12:00:11.000Z">
<meta property="article:modified_time" content="2023-03-14T08:27:55.307Z">
<meta property="article:author" content="Carl Su">
<meta property="article:tag" content="Jetpack">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img2.baidu.com/it/u=2072160848,356224098&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500"><link rel="shortcut icon" href="https://s2.loli.net/2023/03/09/whMHdYkrKoIBnSC.png"><link rel="canonical" href="https://devsu.top/posts/6ee0249e/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?6243425e2ecb037931274c4ca1db3132";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":300},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Carl Su","link":"链接: ","source":"来源: 码行","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: true,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Jetpack -- (一)Lifecycle',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-03-14 16:27:55'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://s2.loli.net/2023/03/09/QrI9mgJ4XlbEPzN.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">169</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">37</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">38</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg fixed" id="page-header" style="background-image: url('https://img2.baidu.com/it/u=2072160848,356224098&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500')"><nav id="nav"><span id="blog-info"><a href="/" title="码行"><img class="site-icon" src="https://s2.loli.net/2023/03/09/whMHdYkrKoIBnSC.png"/><span class="site-name">码行</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Jetpack -- (一)Lifecycle</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-08-05T12:00:11.000Z" title="发表于 2020-08-05 20:00:11">2020-08-05</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-03-14T08:27:55.307Z" title="更新于 2023-03-14 16:27:55">2023-03-14</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/">Android</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Android/Jetpack/">Jetpack</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>6分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Jetpack -- (一)Lifecycle"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="使用Lifecycle解耦页面与组件"><a href="#使用Lifecycle解耦页面与组件" class="headerlink" title="使用Lifecycle解耦页面与组件"></a>使用Lifecycle解耦页面与组件</h2><h3 id="场景：-Chronometer统计页面在前台时间"><a href="#场景：-Chronometer统计页面在前台时间" class="headerlink" title="场景： Chronometer统计页面在前台时间"></a>场景： Chronometer统计页面在前台时间</h3><p>使用Lifecycle之前：</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">lateinit</span> <span class="keyword">var</span> binding: ActivityMainBinding</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">var</span> elapsedTime:<span class="built_in">Long</span> = <span class="number">0</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onCreate</span><span class="params">(savedInstanceState: <span class="type">Bundle</span>?)</span></span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState)</span><br><span class="line"></span><br><span class="line">        binding = ActivityMainBinding.inflate(layoutInflater)</span><br><span class="line">        setContentView(binding.root)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onResume</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.onResume()</span><br><span class="line">        binding.chronometer.apply &#123;</span><br><span class="line">            base = SystemClock.elapsedRealtime()</span><br><span class="line">            start()</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onPause</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.onPause()</span><br><span class="line">        binding.chronometer.apply &#123;</span><br><span class="line">            elapsedTime = SystemClock.elapsedRealtime() - base</span><br><span class="line">            stop()</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>使用Lifecycle之后:</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">MyChronometer</span>(context: Context, attrs: AttributeSet) : Chronometer(context, attrs),LifecycleEventObserver &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">var</span> elapsedTime: <span class="built_in">Long</span> = <span class="number">0</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">startMeter</span><span class="params">()</span></span> &#123;</span><br><span class="line">        base = SystemClock.elapsedRealtime() - elapsedTime</span><br><span class="line">        start()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">stopMeter</span><span class="params">()</span></span> &#123;</span><br><span class="line">        elapsedTime = SystemClock.elapsedRealtime() - <span class="keyword">this</span>.base</span><br><span class="line">        stop()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onStateChanged</span><span class="params">(source: <span class="type">LifecycleOwner</span>, event: <span class="type">Lifecycle</span>.<span class="type">Event</span>)</span></span> &#123;</span><br><span class="line">        <span class="keyword">when</span> (event) &#123;</span><br><span class="line">            Lifecycle.Event.ON_RESUME -&gt; startMeter()</span><br><span class="line">            Lifecycle.Event.ON_PAUSE -&gt; stopMeter()</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>同时需要在Activity的<code>onCreate()</code>中添加:</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line">lifecycle.addObserver(binding.chronometer)</span><br></pre></td></tr></table></figure>



<h2 id="使用LifecycleService解耦Service与组件"><a href="#使用LifecycleService解耦Service与组件" class="headerlink" title="使用LifecycleService解耦Service与组件"></a>使用LifecycleService解耦Service与组件</h2><p>添加依赖:</p>
<figure class="highlight sh"><table><tr><td class="code"><pre><span class="line">implementation <span class="string">&#x27;androidx.lifecycle:lifecycle-extensions:2.2.0&#x27;</span></span><br></pre></td></tr></table></figure>

<p>Observer</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">LocationObserver</span>(serviceContext: Context) : DefaultLifecycleObserver &#123;</span><br><span class="line">    <span class="keyword">companion</span> <span class="keyword">object</span>&#123;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">const</span> <span class="keyword">val</span> TAG = <span class="string">&quot;LocationObserver&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">val</span> context = serviceContext</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">var</span> locationManager: LocationManager? = <span class="literal">null</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">var</span> myLocationListener: LocationListener? = <span class="literal">null</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onCreate</span><span class="params">(owner: <span class="type">LifecycleOwner</span>)</span></span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(owner)</span><br><span class="line">        startLocation()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onDestroy</span><span class="params">(owner: <span class="type">LifecycleOwner</span>)</span></span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.onDestroy(owner)</span><br><span class="line">        stopLocation()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@SuppressLint(<span class="string">&quot;MissingPermission&quot;</span>)</span></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">startLocation</span><span class="params">()</span></span> &#123;</span><br><span class="line">        Log.e(TAG, <span class="string">&quot;startLocation: &quot;</span>, )</span><br><span class="line">        locationManager = context.getSystemService(Context.LOCATION_SERVICE) <span class="keyword">as</span> LocationManager</span><br><span class="line">        myLocationListener = MyLocationListener()</span><br><span class="line">        myLocationListener?.let &#123;</span><br><span class="line">            locationManager?.requestLocationUpdates(</span><br><span class="line">                LocationManager.GPS_PROVIDER,</span><br><span class="line">                <span class="number">3000</span>,<span class="comment">//每三秒获取一次</span></span><br><span class="line">                <span class="number">10f</span>,<span class="comment">//每移动10米获取一次</span></span><br><span class="line">                it</span><br><span class="line">            )</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">stopLocation</span><span class="params">()</span></span> &#123;</span><br><span class="line">        myLocationListener?.let &#123;</span><br><span class="line">            locationManager?.removeUpdates(it)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">class</span> <span class="title class_">MyLocationListener</span> : <span class="type">LocationListener</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">companion</span> <span class="keyword">object</span> &#123;</span><br><span class="line">            <span class="keyword">private</span> <span class="keyword">const</span> <span class="keyword">val</span> TAG = <span class="string">&quot;LocationObserver&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onLocationChanged</span><span class="params">(location: <span class="type">Location</span>)</span></span> &#123;</span><br><span class="line">            Log.e(TAG, <span class="string">&quot;onLocationChanged: <span class="variable">$location</span>&quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>自定义Service继承<code>LifecycleService</code></p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">LocationLifecycleService</span>: <span class="type">LifecycleService</span>() &#123;</span><br><span class="line">    <span class="keyword">companion</span> <span class="keyword">object</span> &#123;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">const</span> <span class="keyword">val</span> TAG = <span class="string">&quot;LocationLifecycleService&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">init</span> &#123;</span><br><span class="line">        Log.e(TAG, <span class="string">&quot;LocationLifecycleService init &quot;</span>)</span><br><span class="line">        <span class="keyword">val</span> locationObserver = LocationObserver( <span class="keyword">this</span>)</span><br><span class="line">        lifecycle.addObserver(locationObserver)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Activity:</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">MainActivity</span> : <span class="type">AppCompatActivity</span>() &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">lateinit</span> <span class="keyword">var</span> binding: ActivityMainBinding</span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onCreate</span><span class="params">(savedInstanceState: <span class="type">Bundle</span>?)</span></span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState)</span><br><span class="line">        binding = ActivityMainBinding.inflate(layoutInflater)</span><br><span class="line">        setContentView(binding.root)</span><br><span class="line">        initClick()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">initClick</span><span class="params">()</span></span> &#123;</span><br><span class="line">        binding.start.setOnClickListener&#123;</span><br><span class="line">            startService(Intent(<span class="keyword">this</span><span class="symbol">@MainActivity</span>,LocationLifecycleService::<span class="keyword">class</span>.java))</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        binding.stop.setOnClickListener&#123;</span><br><span class="line">            stopService(Intent(<span class="keyword">this</span><span class="symbol">@MainActivity</span>,LocationLifecycleService::<span class="keyword">class</span>.java))</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在AndroidManifest.xml中添加权限和注册Service</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">uses-permission</span> <span class="attr">android:name</span>=<span class="string">&quot;android.permission.ACCESS_COARSE_LOCATION&quot;</span> /&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">uses-permission</span> <span class="attr">android:name</span>=<span class="string">&quot;android.permission.ACCESS_FINE_LOCATION&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">application</span></span></span><br><span class="line"><span class="tag">     <span class="attr">android:allowBackup</span>=<span class="string">&quot;true&quot;</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">service</span> <span class="attr">android:name</span>=<span class="string">&quot;.LocationLifecycleService&quot;</span> /&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">application</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h2 id="使用ProcesslifecycleOwner-监听应用程序生命周期"><a href="#使用ProcesslifecycleOwner-监听应用程序生命周期" class="headerlink" title="使用ProcesslifecycleOwner 监听应用程序生命周期"></a>使用ProcesslifecycleOwner 监听应用程序生命周期</h2><ul>
<li>针对整个应用程序的监听，与Activity数量无关</li>
<li>Lifecycle.Event.ON_CREATE只会被调用一次，Lifecycle.Event.ON_DESTROY永远不会被调用</li>
</ul>
<p>添加依赖:</p>
<figure class="highlight groovy"><table><tr><td class="code"><pre><span class="line">implementation <span class="string">&#x27;androidx.lifecycle:lifecycle-process:2.6.0-alpha01&#x27;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">ApplicationObserver</span>: <span class="type">LifecycleEventObserver</span> &#123;</span><br><span class="line">    <span class="keyword">companion</span> <span class="keyword">object</span>&#123;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">const</span> <span class="keyword">val</span> TAG = <span class="string">&quot;ApplicationObserver&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onStateChanged</span><span class="params">(source: <span class="type">LifecycleOwner</span>, event: <span class="type">Lifecycle</span>.<span class="type">Event</span>)</span></span> &#123;</span><br><span class="line">        <span class="keyword">when</span>(event)&#123;</span><br><span class="line">            Lifecycle.Event.ON_CREATE -&gt; Log.e(TAG, <span class="string">&quot;onStateChanged: ON_CREATE&quot;</span>, )</span><br><span class="line">            Lifecycle.Event.ON_START -&gt; Log.e(TAG, <span class="string">&quot;onStateChanged: ON_START&quot;</span>, )</span><br><span class="line">            Lifecycle.Event.ON_RESUME -&gt; Log.e(TAG, <span class="string">&quot;onStateChanged: ON_RESUME&quot;</span>, )</span><br><span class="line">            Lifecycle.Event.ON_PAUSE -&gt; Log.e(TAG, <span class="string">&quot;onStateChanged: ON_PAUSE&quot;</span>, )</span><br><span class="line">            Lifecycle.Event.ON_STOP -&gt; Log.e(TAG, <span class="string">&quot;onStateChanged: ON_STOP&quot;</span>, )</span><br><span class="line">            Lifecycle.Event.ON_DESTROY -&gt; Log.e(TAG, <span class="string">&quot;onStateChanged: ON_DESTROY&quot;</span>, )</span><br><span class="line">            Lifecycle.Event.ON_ANY -&gt; Log.e(TAG, <span class="string">&quot;onStateChanged: &quot;</span>)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>Application中使用</p>
<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">MyApplication</span> : <span class="type">Application</span>() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onCreate</span><span class="params">()</span></span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate()</span><br><span class="line"></span><br><span class="line">        ProcessLifecycleOwner.<span class="keyword">get</span>().lifecycle.addObserver(ApplicationObserver())</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="应用场景"><a href="#应用场景" class="headerlink" title="应用场景:"></a>应用场景:</h2><h3 id="应用启动广告"><a href="#应用启动广告" class="headerlink" title="应用启动广告"></a>应用启动广告</h3><figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">AdvertisingManage</span>: <span class="type">LifecycleEventObserver</span>&#123;</span><br><span class="line">    <span class="keyword">companion</span> <span class="keyword">object</span>&#123;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">const</span> <span class="keyword">val</span> TAG = <span class="string">&quot;AdvertisingManage&quot;</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> advertisingManagerListener: AdvertisingManagerListener? = <span class="literal">null</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">var</span> countDownTimer: CountDownTimer? = <span class="keyword">object</span> : CountDownTimer(<span class="number">5000</span>,<span class="number">1000</span>)&#123;</span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onTick</span><span class="params">(p0: <span class="type">Long</span>)</span></span> &#123;</span><br><span class="line">            Log.e(TAG, <span class="string">&quot;广告剩余<span class="subst">$&#123;(p0 / <span class="number">1000</span>).toInt()&#125;</span>秒&quot;</span>  )</span><br><span class="line">            advertisingManagerListener?.timing((p0 / <span class="number">1000</span>).toInt())</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onFinish</span><span class="params">()</span></span> &#123;</span><br><span class="line">            Log.e(TAG, <span class="string">&quot;广告结束,准备进入主界面&quot;</span> )</span><br><span class="line">            advertisingManagerListener?.enterMainActivity()</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">start</span><span class="params">()</span></span>&#123;</span><br><span class="line">        Log.e(TAG, <span class="string">&quot;开始计时&quot;</span> )</span><br><span class="line">        countDownTimer?.start()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">stop</span><span class="params">()</span></span>&#123;</span><br><span class="line">        Log.e(TAG, <span class="string">&quot;停止计时&quot;</span>, )</span><br><span class="line">        countDownTimer?.cancel()</span><br><span class="line">        countDownTimer = <span class="literal">null</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">interface</span> <span class="title class_">AdvertisingManagerListener</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">fun</span> <span class="title">timing</span><span class="params">(second: <span class="type">Int</span>)</span></span></span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">fun</span> <span class="title">enterMainActivity</span><span class="params">()</span></span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onStateChanged</span><span class="params">(source: <span class="type">LifecycleOwner</span>, event: <span class="type">Lifecycle</span>.<span class="type">Event</span>)</span></span> &#123;</span><br><span class="line">        <span class="keyword">when</span>(event)&#123;</span><br><span class="line">            Lifecycle.Event.ON_CREATE -&gt; start()</span><br><span class="line">            Lifecycle.Event.ON_DESTROY -&gt; stop()</span><br><span class="line">            <span class="keyword">else</span> -&gt; &#123;&#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">AdvertisingActivity</span> : <span class="type">AppCompatActivity</span>() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">lateinit</span> <span class="keyword">var</span> binding: ActivityAdvertisingBinding</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onCreate</span><span class="params">(savedInstanceState: <span class="type">Bundle</span>?)</span></span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState)</span><br><span class="line">        binding = ActivityAdvertisingBinding.inflate(layoutInflater)</span><br><span class="line"></span><br><span class="line">        setContentView(binding.root)</span><br><span class="line"></span><br><span class="line">        <span class="keyword">val</span> advertisingManage = AdvertisingManage()</span><br><span class="line">        advertisingManage.advertisingManagerListener = <span class="keyword">object</span> : AdvertisingManage.AdvertisingManagerListener&#123;</span><br><span class="line">            <span class="meta">@SuppressLint(<span class="string">&quot;SetTextI18n&quot;</span>)</span></span><br><span class="line">            <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">timing</span><span class="params">(second: <span class="type">Int</span>)</span></span> &#123;</span><br><span class="line">                binding.textView.apply &#123;</span><br><span class="line">                    text = <span class="string">&quot;广告剩余<span class="subst">$&#123;second&#125;</span>秒&quot;</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">enterMainActivity</span><span class="params">()</span></span> &#123;</span><br><span class="line">                startActivity(Intent(<span class="keyword">this</span><span class="symbol">@AdvertisingActivity</span>,MainActivity::<span class="keyword">class</span>.java))</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        binding.button.apply &#123;</span><br><span class="line">            setOnClickListener&#123;</span><br><span class="line">                startActivity(Intent(<span class="keyword">this</span><span class="symbol">@AdvertisingActivity</span>,MainActivity::<span class="keyword">class</span>.java))</span><br><span class="line">                finish()</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//在Activity注册Oberver</span></span><br><span class="line">        lifecycle.addObserver(advertisingManage)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="打造一个防止内存泄漏的Dialog"><a href="#打造一个防止内存泄漏的Dialog" class="headerlink" title="打造一个防止内存泄漏的Dialog"></a>打造一个防止内存泄漏的Dialog</h3><figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">TipDialog</span>(context: Context) : Dialog(context),LifecycleObserver&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">init</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (context <span class="keyword">is</span> ComponentActivity)&#123;</span><br><span class="line">            context.lifecycle.addObserver(<span class="keyword">this</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onCreate</span><span class="params">(savedInstanceState: <span class="type">Bundle</span>?)</span></span> &#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState)</span><br><span class="line">        setContentView(R.layout.dialog_tip)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)</span></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">onDestroy</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (isShowing)&#123;</span><br><span class="line">            dismiss()</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="打造一个支持Lifecycle的MapView"><a href="#打造一个支持Lifecycle的MapView" class="headerlink" title="打造一个支持Lifecycle的MapView"></a>打造一个支持Lifecycle的MapView</h3><figure class="highlight kotlin"><table><tr><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">GeoMapView</span>(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs),LifecycleEventObserver &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">var</span> mapView: MapView? = <span class="literal">null</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">init</span> &#123;</span><br><span class="line">        mapView = MapView(context)</span><br><span class="line">        addView(mapView)</span><br><span class="line">        <span class="keyword">if</span> (context <span class="keyword">is</span> ComponentActivity)&#123;</span><br><span class="line">            context.lifecycle.addObserver(<span class="keyword">this</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        Timber.e(<span class="string">&quot;constructor method invoked&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取真正的mapView</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">fun</span> <span class="title">getMapView</span><span class="params">()</span></span>: MapView? &#123;</span><br><span class="line">        <span class="keyword">return</span> mapView</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">override</span> <span class="function"><span class="keyword">fun</span> <span class="title">onStateChanged</span><span class="params">(source: <span class="type">LifecycleOwner</span>, event: <span class="type">Lifecycle</span>.<span class="type">Event</span>)</span></span> &#123;</span><br><span class="line">        <span class="keyword">when</span>(event.targetState)&#123;</span><br><span class="line">            Lifecycle.State.CREATED -&gt; onCreate(source)</span><br><span class="line">            Lifecycle.State.DESTROYED -&gt; onDestroy()</span><br><span class="line">            Lifecycle.State.RESUMED -&gt; onResume()</span><br><span class="line">            <span class="keyword">else</span> -&gt; &#123;&#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">onDestroy</span><span class="params">()</span></span>&#123;</span><br><span class="line">        Timber.e(<span class="string">&quot;onDestroy&quot;</span>)</span><br><span class="line">        mapView?.dispose()</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">onResume</span><span class="params">()</span></span>&#123;</span><br><span class="line">        mapView?.resume()</span><br><span class="line">        Timber.e(<span class="string">&quot;onResume&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">fun</span> <span class="title">onCreate</span><span class="params">(source: <span class="type">LifecycleOwner</span>)</span></span>&#123;</span><br><span class="line">        Timber.e(<span class="string">&quot;onCreate&quot;</span>)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://devsu.top">Carl Su</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://devsu.top/posts/6ee0249e/">https://devsu.top/posts/6ee0249e/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://devsu.top" target="_blank">码行</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Jetpack/">Jetpack</a></div><div class="post_share"><div class="social-share" data-image="https://img2.baidu.com/it/u=2072160848,356224098&amp;fm=253&amp;fmt=auto&amp;app=138&amp;f=JPEG?w=889&amp;h=500" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/2f69bde1/" title="Jetpack -- (三)LiveData"><img class="cover" src="https://picnew7.photophoto.cn/20130830/dongman-katongrenwutupian-08868140_1.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Jetpack -- (三)LiveData</div></div></a></div><div class="next-post pull-right"><a href="/posts/ddcdc262/" title="Android自定义View-04 属性动画进阶"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Android自定义View-04 属性动画进阶</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/e656a1a7/" title="Jetpack架构组件"><img class="cover" src="https://img1.baidu.com/it/u=3883901366,3394399596&fm=253&fmt=auto&app=120&f=PNG?w=715&h=339" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Jetpack架构组件</div></div></a></div><div><a href="/posts/b74e9fe6/" title="LiveData和LiveData观察者"><img class="cover" src="https://s2.loli.net/2023/03/15/V2cZYjrmiHPwGCT.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">LiveData和LiveData观察者</div></div></a></div><div><a href="/posts/25183f3/" title="Data binding with ViewModel and LiveData"><img class="cover" src="https://img1.baidu.com/it/u=1761090025,1766685221&fm=253&fmt=auto&app=138&f=JPG?w=717&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Data binding with ViewModel and LiveData</div></div></a></div><div><a href="/posts/62149ceb/" title="LiveData transformations"><img class="cover" src="https://img1.baidu.com/it/u=1903792554,3461942085&fm=253&fmt=auto&app=120&f=JPEG?w=887&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">LiveData transformations</div></div></a></div><div><a href="/posts/7b4995aa/" title="Android Navigation错误"><img class="cover" src="https://img2.baidu.com/it/u=329469198,1322569813&fm=253&fmt=auto&app=138&f=JPG?w=800&h=500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-08-05</div><div class="title">Android Navigation错误</div></div></a></div><div><a href="/posts/5f8a375b/" title="Jetpack——DataBinding使用-RecyclerView"><img class="cover" src="https://s2.loli.net/2023/03/15/ao7NrF4I1cWe3UR.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-05</div><div class="title">Jetpack——DataBinding使用-RecyclerView</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div><div id="comment-switch"><span class="first-comment">Valine</span><span class="switch-btn"></span><span class="second-comment">Disqus</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div><div><div id="disqus_thread"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8Lifecycle%E8%A7%A3%E8%80%A6%E9%A1%B5%E9%9D%A2%E4%B8%8E%E7%BB%84%E4%BB%B6"><span class="toc-number">1.</span> <span class="toc-text">使用Lifecycle解耦页面与组件</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9C%BA%E6%99%AF%EF%BC%9A-Chronometer%E7%BB%9F%E8%AE%A1%E9%A1%B5%E9%9D%A2%E5%9C%A8%E5%89%8D%E5%8F%B0%E6%97%B6%E9%97%B4"><span class="toc-number">1.1.</span> <span class="toc-text">场景： Chronometer统计页面在前台时间</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8LifecycleService%E8%A7%A3%E8%80%A6Service%E4%B8%8E%E7%BB%84%E4%BB%B6"><span class="toc-number">2.</span> <span class="toc-text">使用LifecycleService解耦Service与组件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8ProcesslifecycleOwner-%E7%9B%91%E5%90%AC%E5%BA%94%E7%94%A8%E7%A8%8B%E5%BA%8F%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="toc-number">3.</span> <span class="toc-text">使用ProcesslifecycleOwner 监听应用程序生命周期</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="toc-number">4.</span> <span class="toc-text">应用场景:</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BA%94%E7%94%A8%E5%90%AF%E5%8A%A8%E5%B9%BF%E5%91%8A"><span class="toc-number">4.1.</span> <span class="toc-text">应用启动广告</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%93%E9%80%A0%E4%B8%80%E4%B8%AA%E9%98%B2%E6%AD%A2%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F%E7%9A%84Dialog"><span class="toc-number">4.2.</span> <span class="toc-text">打造一个防止内存泄漏的Dialog</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%93%E9%80%A0%E4%B8%80%E4%B8%AA%E6%94%AF%E6%8C%81Lifecycle%E7%9A%84MapView"><span class="toc-number">4.3.</span> <span class="toc-text">打造一个支持Lifecycle的MapView</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2018 - 2023 By Carl Su</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">学无止境</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="聊天"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: '',
      appKey: '',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script><script>function loadDisqus () {
  var disqus_config = function () {
    this.page.url = 'https://devsu.top/posts/6ee0249e/'
    this.page.identifier = '/posts/6ee0249e/'
    this.page.title = 'Jetpack -- (一)Lifecycle'
  };

  window.disqusReset = () => {
    DISQUS.reset({
      reload: true,
      config: disqus_config
    })
  }

  if (window.DISQUS) disqusReset()
  else {
    (function() { 
      var d = document, s = d.createElement('script');
      s.src = 'https://.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      (d.head || d.body).appendChild(s);
    })();
  }

  document.getElementById('darkmode').addEventListener('click', () => {
    setTimeout(() => window.disqusReset(), 200)
  })
}

if ('Valine' === 'Disqus' || !true) {
  if (true) btf.loadComment(document.getElementById('disqus_thread'), loadDisqus)
  else loadDisqus()
} else {
  function loadOtherComment () {
    loadDisqus()
  }
}
</script></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>